package com.server.utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.Map;

public class JwtUtils {
    private static final long time = 1000 * 60 * 60 * 24 * 15;
    //15day
    private static final String signature = "abc123456";

    public static String createToken(Map<String, Object> claims) {
        String jwt = Jwts.builder()
                .addClaims(claims)
                .signWith(SignatureAlgorithm.HS256, signature)
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .compact();
        return jwt;
    }

    public static String parseToken(String token) throws Exception {
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
        } catch (Exception e) {
            return null;
        }
        Claims claims = claimsJws.getBody();
        return (String) claims.get("nickname");
    }

    /**
     * 解析JWT令牌
     * @param jwt JWT令牌
     * @return JWT第二部分负载 payload 中存储的内容
     */
    public static Claims parseJWT(String jwt){
        Claims claims = Jwts.parser()
                .setSigningKey(signature)
                .parseClaimsJws(jwt)
                .getBody();
        return claims;
    }


}
